package com.xique.client.service.biz.service.impl;

import com.xique.client.api.domain.ClientUserInfo;
import com.xique.client.api.model.LoginClientUser;
import com.xique.client.bean.domain.Client;
import com.xique.client.bean.domain.ClientUser;
import com.xique.client.bean.domain.ClientUserInform;
import com.xique.client.bean.request.ClientChangePasswordRequest;
import com.xique.client.bean.request.ClientRelieveRequest;
import com.xique.client.service.biz.service.IClientLoginBizService;
import com.xique.client.service.biz.service.IClientLoginInfoBizService;
import com.xique.client.service.service.IClientService;
import com.xique.client.service.service.IClientUserInfoService;
import com.xique.client.service.service.IClientUserService;
import com.xique.common.core.constant.Constants;
import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.enums.UserStatus;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.security.service.ClientTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author shd
 * @create 2021/7/31 16:22
 */
@Service
public class ClientLoginBizServiceImpl implements IClientLoginBizService {

    @Autowired
    private ClientTokenService clientTokenService;

    @Autowired
    private IClientLoginInfoBizService clientLoginInfoBizService;

    @Autowired
    private IClientUserInfoService clientUserInfoService;

    @Autowired
    private IClientService clientService;

    @Autowired
    private IClientUserService clientUserService;

    /**
     * 换班登录
     * @author shd
     * @date 2021/7/31 14:01
     * @param request
     * @return com.xique.common.core.web.domain.AjaxResult
     */
    @Override
    public AjaxResult relieve(ClientRelieveRequest request) {

        Long clientId = SecurityUtils.getClientId();

        AjaxResult result = checkClientRelieveRequest(request, clientId);
        if (!AjaxResult.isSuccess(result)) {
            return result;
        }

        String loginName = request.getLoginName();
        String oldLoginName = SecurityUtils.getUsername();

        // 删除当前用户登录信息
        clientTokenService.delLoginUser(SecurityUtils.getToken());
        // 添加登出日志
        clientLoginInfoBizService.addLoginInfo(clientId, oldLoginName, Constants.LOGOUT, "退出成功");

        ClientUserInfo user = clientUserInfoService.selectClientUserByLoginName(loginName);
        LoginClientUser loginClientUser = new LoginClientUser();
        loginClientUser.setClientUserInfo(user);
        loginClientUser.setClientId(clientId);
        // 存储登录信息
        Map<String, Object> map = clientTokenService.createToken(loginClientUser);

        // 更新岗亭登录用户信息
        Client update = new Client();
        update.setId(clientId);
        update.setLoginUserId(user.getId());
        update.setLoginUserName(user.getLoginName());
        update.setLoginTime(DateUtils.getNowDate());
        clientService.updateClient(update);

        // 添加登录日志
        clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_SUCCESS, "登录成功");

        return AjaxResult.success(map);
    }

    private AjaxResult checkClientRelieveRequest(ClientRelieveRequest request, Long clientId) {
        String loginName = request.getLoginName();
        String password = request.getPassword();
        String oldLoginName = SecurityUtils.getUsername();

        if (loginName.equals(oldLoginName)) {
            return AjaxResult.error("登录用户：" + loginName + " 已登录当前岗亭");
        }

        ClientUserInfo user = clientUserInfoService.selectClientUserByLoginName(loginName);
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("登录用户：" + loginName + " 不存在");
        }
        //判断当前用户是否是该岗亭用户
        ClientUser search = new ClientUser();
        search.setUserId(user.getId());
        search.setClientId(clientId);
        ClientUser clientUser = clientUserService.selectOne(search);
        if (null == clientUser) {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "岗亭没有此用户");
            return AjaxResult.error("岗亭没有此用户");
        }
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(loginName, password))
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户/密码必须填写");
            return AjaxResult.error("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            return AjaxResult.error("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (loginName.length() < UserConstants.USERNAME_MIN_LENGTH
                || loginName.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户名不在指定范围");
            return AjaxResult.error("用户名不在指定范围");
        }
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            return AjaxResult.error("对不起，您的账号：" + loginName + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            return AjaxResult.error("对不起，您的账号：" + loginName + " 已停用");
        }
        if (!SecurityUtils.matchesPasswordNoEncoded(password, user.getPassword()))
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户密码错误");
            return AjaxResult.error("用户不存在/密码错误");
        }
        return AjaxResult.success();
    }

    /**
     * 修改密码
     * @author shd
     * @date 2021/7/31 16:34
     * @param request
     * @return com.xique.common.core.web.domain.AjaxResult
     */
    @Override
    public AjaxResult changePassword(ClientChangePasswordRequest request) {

        AjaxResult result = checkClientChangePasswordRequest(request);
        if (!AjaxResult.isSuccess(result)) {
            return result;
        }

        // 更新用户密码
        LoginClientUser loginClientUser = clientTokenService.getLoginUser();
        ClientUserInfo user = loginClientUser.getClientUserInfo();

        ClientUserInform update = new ClientUserInform();
        update.setId(user.getId());
        update.setPassword(request.getNewPassword());
        clientUserInfoService.updateClientUser(update);

        // 更新redis信息
        user.setPassword(request.getNewPassword());
        loginClientUser.setClientUserInfo(user);
        clientTokenService.refreshToken(loginClientUser);

        return AjaxResult.success();
    }

    private AjaxResult checkClientChangePasswordRequest(ClientChangePasswordRequest request) {
        String oldPassword = request.getOldPassword();
        String newPassword = request.getNewPassword();
        if (StringUtils.isAnyBlank(oldPassword, newPassword))
        {
            return AjaxResult.error("原用户/新密码必须填写");
        }
        if (oldPassword.length() < UserConstants.PASSWORD_MIN_LENGTH
                || oldPassword.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            return AjaxResult.error("用户原密码不在指定范围");
        }
        if (newPassword.length() < UserConstants.PASSWORD_MIN_LENGTH
                || newPassword.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            return AjaxResult.error("用户新密码不在指定范围");
        }
        ClientUserInfo user = clientTokenService.getLoginUser().getClientUserInfo();
        if (!SecurityUtils.matchesPasswordNoEncoded(oldPassword, user.getPassword()))
        {
            return AjaxResult.error("原密码错误");
        }
        return AjaxResult.success();
    }
}
